#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

#include "global.h"
#include "threadpool/include/thread-pool.h"


void *workFunction(void *args)
{
    //printf("Thread PID %p Execute Task %d!\n", pthread_self(), *(int *) args);
    //printf("Thread PID %p Receive data: %s!\n", pthread_self(), (char *) args);

    //printf("deal data %s\n", (char *) args);
    log_i("Thread PID %p Receive data: %s!\n", pthread_self(), (char *) args);

//    struct timespec sleep_time = {0, 1000 * 1000 * 100};
//    nanosleep(&sleep_time, NULL);

    return NULL;
}

int udp_service()
{
    log_i("Thread PID Start Service!\n");

    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(fd == -1)
    {
        perror("socket");
        exit(0);
    }

    struct sockaddr_in addr;
    unsigned short int port = (unsigned short int)g_udp_port;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret == -1)
    {
        perror("bind");
        exit(-1);
    }
    printf("bind port %d, wait client connect ...\n", port);

    char ipbuf[64];
    struct sockaddr_in cliaddr;
    unsigned int len = sizeof(cliaddr);

    while(1)
    {
        char *buf = (char *) malloc(1024);
        memset(buf, 0, 1024);
        int rlen = recvfrom(fd, buf, 1024, 0, (struct sockaddr*)&cliaddr, &len);
        printf("receive data length is %d", rlen);
        printf("client info, ip: %s, port: %d\n",
               inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, ipbuf, sizeof(ipbuf)),
               ntohs(cliaddr.sin_port));
        printf("recvfrom client say: %s\n", buf);
        log_i("recvfrom client say: %s\n", buf);

        submitTask(g_pool, workFunction, buf);

        //sendto(fd, buf, rlen, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
    }

    close(fd);

    return 0;
}

//
//int main()
//{
//    test01();
//    return 0;
//}
